var express = require('express');
var router = express.Router();
const {Course} = require('../models');
const {Op} = require('sequelize')
const { failure, success, NotFoundError } = require('../utils/response');

// 按照课程名称搜索课程接口
router.get('/',async (req,res,next) => {
    try {
        const query = req.query
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        const offset = (currentPage-1)*pageSize
        const condition = {
            attributes:{exclude:['categoryId','userId','content']},
            order:[['id','DESC']],
            limit:pageSize,
            offset:offset,
        }

        if(query.name){
            condition.where = {
                name:{
                    [Op.like]:`%${query.name}%`
                }
            }
        }

        const {count,rows} = await Course.findAndCountAll(condition) //查询articles表中的所有数据，是异步操作
        
        success(res,'查询课程成功',{
            articles:rows,
            pagination:{
                total:count,
                currentPage,
                pageSize,
            }
        })
    } catch (error) {
        failure(res,error)
    }
    
})

module.exports = router